package geektime.spring.springbucks.waiter.service;

import geektime.spring.springbucks.waiter.mapper.CoffeeOrderMapper;
import geektime.spring.springbucks.waiter.mapper.OrderCoffeeMapper;
import geektime.spring.springbucks.waiter.model.Coffee;
import geektime.spring.springbucks.waiter.model.CoffeeOrder;
import geektime.spring.springbucks.waiter.model.OrderState;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;

@Service
@Transactional
@Slf4j
public class CoffeeOrderService {

    @Resource
    private CoffeeOrderMapper coffeeOrderMapper;

    @Resource
    private OrderCoffeeMapper orderCoffeeMapper;

    public CoffeeOrder get(Long id) {
        return coffeeOrderMapper.getOne(id);
    }

    @Transactional(rollbackFor = Exception.class)
    public CoffeeOrder createOrder(String customer, Coffee...coffee) {
        CoffeeOrder order = CoffeeOrder.builder()
                .customer(customer)
                .items(new ArrayList<>(Arrays.asList(coffee)))
                .state(OrderState.INIT)
                .build();
        // 保存订单信息
        coffeeOrderMapper.save(order);
        // 保存订单和咖啡的关联信息
//        Arrays.asList(coffee).stream().forEach(coffee1 -> {
//            orderCoffeeMapper.save(order.getId(),coffee1.getId());
//        });
        orderCoffeeMapper.saveList(order);

        log.info("New Order: {}", order);
        return order;
    }

    @Transactional(rollbackFor = Exception.class)
    public boolean updateState(CoffeeOrder order, OrderState state) {
        if (state.compareTo(order.getState()) <= 0) {
            log.warn("Wrong State order: {}, {}", state, order.getState());
            return false;
        }
        order.setState(state);
        coffeeOrderMapper.updateOrderState(order);
        log.info("Updated Order: {}", order);
        return true;
    }

    @Transactional(rollbackFor = Exception.class)
    public boolean deleteOrder (CoffeeOrder order) {

        if(!order.getState().equals(OrderState.INIT)){
            log.warn("Wrong State order: {}", order.getState());
            return false;
        }

        coffeeOrderMapper.deleteOrder(order);
        log.info("delete Order: {}", order);
        return true;
    }

}
